#include "ZipWriter.h"
#include "Util.h"
#include <stdio.h>

using namespace std;

ZipWriter::~ZipWriter()
{
    if(this->output_.is_open())
        this->output_.close();
}

void ZipWriter::write(std::vector<FileHeader*> fileHeaderList, EndOfCentralDirectory* endOfCentralDirectory, const char* destinyPath, const char* fileName)
{
    std::string outputPath = destinyPath;
    outputPath += "/";
    outputPath += fileName;

    this->output_.open(outputPath.c_str(), ios::out | ios::binary);
    writeFileHeaders(fileHeaderList);
    writeCentralDirectories(fileHeaderList);
    endOfCentralDirectory->offsetOfStartOfCentralDir_ = this->offsetCentralDirectory;
    endOfCentralDirectory->sizeOfCentralDir_ = this->centralDirectoriesSize;
    this->output_ << *endOfCentralDirectory;
    this->output_.close();
}

void ZipWriter::writeFileHeaders(std::vector<FileHeader*> fileHeaderList)
{
    for(std::vector<FileHeader*>::iterator fileHeadIt = fileHeaderList.begin();
            fileHeadIt != fileHeaderList.end(); fileHeadIt++)
    {
        FileHeader* fileHeader = *fileHeadIt;
        fileHeader->centralDirectory_->relativeOffset_ = this->output_.tellp();
        this->output_ << *fileHeader;
    }
    
    this->offsetCentralDirectory = this->output_.tellp();
}

void ZipWriter::writeCentralDirectories(std::vector<FileHeader*> fileHeaderList)
{
    for(std::vector<FileHeader*>::iterator fileHeadIt = fileHeaderList.begin();
            fileHeadIt != fileHeaderList.end(); fileHeadIt++)
    {
        FileHeader* fileHeader = *fileHeadIt;
        output_ << *fileHeader->centralDirectory_;
        this->centralDirectoriesSize += fileHeader->centralDirectory_->size();
    }
}